package common;
import java.io.IOException;
import java.security.DigestInputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.DecimalFormat;

public class Util
{
	private static MessageDigest hasher;

	public static String getNiceFileSize(long size)
	{
		String[] postfix = {"B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"};
		int count = 0;
		int remainder = 0;
		while(size >=1024)
		{
			remainder = (int)(size - (size / 1024) * 1024);
			size /= 1024;
			count++;
		}
		
		if(count == 0 || remainder == 0)
		{
			return size + postfix[count];
		}
		else if(size < 10)
		{
			DecimalFormat df = new DecimalFormat(".##");
			return size + df.format((double) remainder / 1024) + postfix[count];
		}
		else if(size < 100)
		{
			DecimalFormat df = new DecimalFormat(".#");
			return size + df.format((double) remainder / 1024) + postfix[count];
		}
		else
		{
			return size + postfix[count];
		}
	}

	public static byte[] convertHexHashcodeToByteArray(String hashcode)
	{
		byte[] r = new byte[hashcode.length() / 2];
		for (int i = 0; i < r.length; i++)
		{
			r[i] = (byte) Integer.parseInt(hashcode.substring(i*2, i*2+2), 16);
		}
		return r;
	}

	public static String convertByteArrayHashcodeToHex(byte[] hashcode)
	{
		StringBuilder sb = new StringBuilder();
		for (byte b : hashcode)
		{
			String a = Integer.toHexString(b & 0xFF);
			if(a.length() == 1) //as Integer.toHexString doesn't give leading 0s
			{
				a = "0" + a;
			}
			sb.append(a);
		}
		return sb.toString();
	}

	public static int getChunkSize(long size)
	{
		return Math.min(Math.max((int) Math.pow(2, (int) (Math.log(size / 100) / Math.log(2))), 128*1024), 4*1024*1024);
	}
	
	public static String getHashCode(DigestInputStream data)
	{
		try
		{
			if(hasher == null)
				hasher = MessageDigest.getInstance("MD5");
		
			hasher.reset();
		}
		catch (NoSuchAlgorithmException e)
		{
			throw new Error("MD5 capabilities not available!");
		}
		
		data.setMessageDigest(hasher);
		data.on(true);
		try
		{
			int d = 0;
			while(d != -1)
				d = data.read();
		}
		catch(IOException e){}
		
		return convertByteArrayHashcodeToHex(hasher.digest());
	}

}
